import 'package:flutter/material.dart';

/// 更多的文件组件
class TextMaxLinesWdiget extends StatefulWidget {
  const TextMaxLinesWdiget({super.key, required this.content, this.maxLines});

  final String content;
  final int? maxLines;

  @override
  State<TextMaxLinesWdiget> createState() => _TextMaxLinesWdigetState();
}

class _TextMaxLinesWdigetState extends State<TextMaxLinesWdiget> {
  // 内容
  late final String _content;

  // 最大行数
  late final int _maxLines;

  // 是否展开
  bool _isExpandsion = false;

  @override
  void initState() {
    super.initState();
    _content = widget.content;
    _maxLines = widget.maxLines ?? 3;
  }

  @override
  Widget build(BuildContext context) {
    return _mainView();
  }

  // 主视图
  Widget _mainView() {
    return LayoutBuilder(
        builder: (BuildContext context, BoxConstraints constraints) {
      // 将 [TextSpan] 树绘制到 [Canvas] 中的对象
      final TextPainter textPainter = TextPainter(
        text: TextSpan(
          text: _content,
          style: TextStyle(
            fontSize: 15,
            color: Colors.black54,
          ),
        ),
        maxLines: _maxLines,
        textDirection: TextDirection.ltr,
      )..layout(
        maxWidth: constraints.maxWidth,
      );

      // 1、不展开
      if (_isExpandsion == false) {
        List<Widget> ws = [];
        // 1.1 检查是否超出高度
        if (textPainter.didExceedMaxLines && _isExpandsion == false) {
          ws.add(
            Text(
              _content,
              maxLines: _maxLines,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(
                fontSize: 15,
                color: Colors.black54,
              ),
            ),
          );

          ws.add(
            GestureDetector(
              onTap: () {
                _doExpansion();
              },
              child: Text(
                "全文",
                style: TextStyle(
                  fontSize: 15,
                  color: Colors.blue,
                ),
              ),
            ),
          );
        } else {
          // 1.2 不超出显示全部

          ws.add(
            Text(
              _content,
              style: TextStyle(
                fontSize: 15,
                color: Colors.blue,
              ),
            ),
          );
        }

           return Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: ws,
          );
      } else {
        // 2、展开显示全部
        return Text(
          _content,
          style: TextStyle(
            fontSize: 15,
            color: Colors.black54,
          ),
        );
      }
    });
  }


  void _doExpansion(){
    setState(() {
      _isExpandsion = !_isExpandsion;
    });
  }

}
